<template>
  <section class="shenghuohuiEdit">
    <el-dialog :title="dialogtitle" :visible.sync="dialogVisible" width="98%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false" append-to-body>
      <el-form v-if="!infoLoading" ref="postForm" :model="postForm" :rules="rules" class="form-container">
        <div id="shenghuohuiEditTable">
          <table cellspacing="0" cellpadding="0" class="mytable">
            <tr>
              <th>通报时间</th>
              <td>
                <el-form-item prop="tongbaoshijian">
                  <el-date-picker v-model="postForm.tongbaoshijian" placeholder="请选择时间" value-format="yyyy-MM-dd" />
                </el-form-item>
              </td>
              <th>通报方式</th>
              <td>
                <el-form-item prop="tongbaofangshi">
                  <el-select v-model="postForm.tongbaofangshi" placeholder="请选择" style="width:200px;">
                    <el-option v-for="(item, index) in depts" :key="'1_'+index" :label="(index+1)+'.'+item" :value="item" />
                  </el-select>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <th>通报范围</th>
              <td colspan="3">
                <el-form-item prop="tongbaofanwei">
                  <el-input v-model="postForm.tongbaofanwei" style="width:100%" :maxlength="100" />
                </el-form-item>
              </td>
            </tr>
            <tr>
              <th>通报稿</th>
              <td colspan="3">
                <el-form-item prop="upload">
                  <el-upload
                    style="width:800px"
                    ref="upload"
                    :action="this.$http.defaults.baseURL+this.$http.defaults.shenghuohuiAPI +'api/newFileInfo/upload/'"
                    :on-success="handleUploadSucc"
                    :on-remove="handleRemove"
                    :before-remove="beforeRemove"
                    :on-error="uploadError"
                    :multiple="true"
                    :file-list="fileListEdit"
                    :before-upload="beforeUpload"
                    accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-works,.wps"
                  >
                    <el-button type="primary">上传</el-button>
                    <div slot="tip" class="el-upload__tip">注：支持上传word/pdf/wps文件</div>
                    <div style="clear:both" />
                  </el-upload>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <th>备注</th>
              <td colspan="3">
                <el-input v-model="postForm.remark" style="width:100%" :maxlength="shhRemarkLength" />
              </td>
            </tr>
            <tr>
              <th></th>
              <td colspan="3">
                <el-button type="primary" :loading="loading" @click="submitForm">保存</el-button>
              </td>
            </tr>
          </table>
        </div>
      </el-form>
    </el-dialog>
    <div v-if="pageLoading" style="margin:20px;">正在加载...</div>
    <div v-else>
      <div style="margin:10px;"><span style="font-weight:bolder;padding-right:20px;">通报民主生活会召开情况</span>
        <el-button-group>
          <el-button type="success" @click="addData" icon="el-icon-plus">新增</el-button>
        </el-button-group>
        <el-button-group>
          <el-button type="primary" icon="el-icon-arrow-up" :loading="btnLoading" @click="moveData(true)" :disabled="!moveUpFlag">上移</el-button>
          <el-button type="primary" icon="el-icon-arrow-down" :loading="btnLoading" @click="moveData(false)" :disabled="!moveDownFlag">下移</el-button>
        </el-button-group>
      </div>
      <el-table :data="tableData" highlight-current-row v-loading="listLoading" style="width: 100%;" :height="tableHeight" border ref="multipleTable" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40" />
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="Tongbaoshijian" label="通报时间" width="120" />
        <el-table-column prop="tongbaofangshi" label="通报方式" width="200" />
        <el-table-column prop="tongbaofanwei" label="通报范围" min-width="200" />
        <el-table-column prop="fileList" label="通报稿" min-width="200">
          <template slot-scope="scope">
              <div v-for="(item,index) in scope.row.fileList" :key="'file_'+scope.row.$index+'_'+index">
                <a :href="$http.defaults.baseURL+$http.defaults.shenghuohuiAPI +'api/newFileInfo/download?download=true&id='+item.id" target="_blank">{{item.fileName}}{{item.fileType?'.'+item.fileType:''}}</a>
                 <template v-if="item.fileType==='pdf'"><i style="cursor: pointer;" class="el-icon-search" @click="download(item.id)" /></template>
              </div>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="120" />
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button type="primary" @click="modData(scope.row.id)" size="medium" style="margin:10px 0;" icon="el-icon-edit">修改</el-button>
            <el-popconfirm title="确定删除该信息吗？" @confirm="removeData(scope.row.id)" style="margin:10px 0;">
              <el-button slot="reference" type="danger" size="medium" :loading="btnLoading" icon="el-icon-delete">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </section>
</template>
<script>
import global from '../Global'
const defaultForm = {
  tongbaoshijian: '',
  tongbaofangshi: '',
  tongbaofanwei: '',
  remark: '',
  id: null
}
export default {
  props: {
    timestamp: ''
  },
  data () {
    const validateRequire = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      depts: ['会议通报', '印发书面通报稿', '网上贴出通报稿', '其他方式'],
      pageLoading: true,
      fileList: [],
      fileListEdit: [],
      files: [],
      shhRemarkLength: global.shhRemarkLength,
      shhItemLength: global.shhItemLength,
      moveUpFlag: false,
      moveDownFlag: false,
      leaders: [],
      tableName: 'newHhTongbao',
      dialogVisible: false,
      dialogtitle: '新增',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        tongbaoshijian: [{ validator: validateRequire }],
        tongbaofangshi: [{ validator: validateRequire }],
        tongbaofanwei: [{ validator: validateRequire }]
      },
      tableHeight: 100,
      multipleSelection: [],
      btnLoading: false,
      listLoading: false,
      tableData: [],
      index: null
    }
  },
  watch: {
    timestamp (val) {
      this.pageLoading = true
      this.getData()
    }
  },
  methods: {
    beforeUpload (file) {
      console.log('文件类型')
      console.log(file.name)
      const isFormat = file.name.indexOf('.docx') > 0 || file.name.indexOf('.doc') > 0 || file.name.indexOf('.pdf') > 0 || file.name.indexOf('.DOCX') > 0 || file.name.indexOf('.DOC') > 0 || file.name.indexOf('.PDF') > 0 || file.name.indexOf('.wps') > 0 || file.name.indexOf('.WPS') > 0
      const isLt500M = file.size / 1024 / 1024 < 60
      if (!isLt500M) {
        this.$message.error('单个附件不能超过60M!')
      } else {
        this.saveloading = true
      }
      if (!isFormat) {
        this.$message.error('附件格式必须为word、pdf、wps!')
      } else {
        this.saveloading = true
      }
      return isFormat && isLt500M
    },
    formatFiles (files) {
      if (files && files.length > 0) {
        const newfiles = []
        for (let i = 0; i < files.length; i++) {
          newfiles.push({ name: files[i].fileName + '.' + files[i].fileType, id: files[i].id })
        }
        console.log(newfiles)
        return newfiles
      }
    },
    formatSuccList (fileList) {
      if (fileList && fileList.length > 0) {
        const newfiles = []
        let i = fileList.length - 1
        if (fileList[i].response) {
          newfiles.push({ name: fileList[i].response.result[0].fileName + '.' + fileList[i].response.result[0].fileType, id: fileList[i].response.result[0].id })
        } else {
          newfiles.push(fileList[i])
        }
        console.log(newfiles)
        return newfiles
      }
    },
    removeFile (id) {
      this.files.splice(this.files.findIndex(item => item.id === id), 1)
    },
    handleUploadSucc (response, file, fileList, flag) {
      this.saveloading = false
      if (response.success) {
        this.files.push({id: response.result[0].id, fileName: response.result[0].fileName, fileType: response.result[0].fileType})
        // this.fileList = this.formatSuccList(fileList)
        this.$message({
          message: '上传成功！' + response.message,
          type: 'success'
        })
      } else {
        this.$message({
          message: '上传失败:' + response.message,
          type: 'error'
        })
      }
    },
    beforeRemove (file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`确定删除 ${file.name}？`)
      }
    },
    handleRemove (file, fileList) {
      console.log('file')
      console.log(file)
      if (file && file.status === 'success') {
        let fileid = file.id ? file.id : file.response.result[0].id
        const url = 'api/newFileInfo/remove?id=' + fileid
        this.$http.get(this.$http.defaults.shenghuohuiAPI + url).then(res => {
          console.log('删除成功:', res)
          if (res.data.success === true) {
            this.files = this.files.filter(item => item.id !== fileid)
            // this.fileList = this.formatFiles(this.files)
            this.$message({
              message: '删除成功！',
              type: 'success'
            })
          }
        })
      }
    },
    uploadError (err) {
      this.saveloading = false
      console.log(err)
      this.$message({
        message: '上传失败:' + err,
        type: 'error'
      })
    },
    download (id) {
      window.open(this.$http.defaults.baseURL + this.$http.defaults.shenghuohuiAPI + 'api/newFileInfo/download?id=' + id)
    },
    handlePreview (file) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(this.$http.defaults.baseURL + this.$http.defaults.shenghuohuiAPI + 'api/newFileInfo/download?download=true&id=' + file.id, file.name)
      } else {
        var link = document.createElement('a')
        link.download = file.name
        link.href = this.$http.defaults.baseURL + this.$http.defaults.shenghuohuiAPI + 'api/newFileInfo/download?download=true&id=' + file.id
        link.click()
        console.log(this.$http.defaults.shenghuohuiAPI + 'api/newFileInfo/download?download=true&id=' + file.id)
        window.URL.revokeObjectURL(link.href)
      }
    },
    moveData (flag) {
      this.btnLoading = true
      let para = {
        id: this.multipleSelection[0].id,
        shenghuohuiunitId: localStorage.getItem('shenghuohuiunitId'),
        up: flag
      }
      this.$http.post(this.$http.defaults.shenghuohuiAPI + `api/` + this.tableName + `/updateOrder`, para).then(response => {
        console.log(response.data.success)
        if (response.data.success === true) {
          this.btnLoading = false
          this.getData(this.multipleSelection[0].id)
        } else {
          console.log('调整顺序失败:' + response.data.message)
          this.$message({
            message: '调整顺序失败:' + response.data.message,
            type: 'error'
          })
          this.btnLoading = false
        }
      }).catch(error => {
        console.log(error)
        this.$message({
          message: '调整顺序失败:' + error,
          type: 'error'
        })
        this.btnLoading = false
      })
    },
    handleSelectionChange (val) {
      this.moveUpFlag = false
      this.moveDownFlag = false
      this.multipleSelection = val
      if (this.multipleSelection.length === 1) {
        this.moveUpFlag = true
        this.moveDownFlag = true
        if (this.tableData.findIndex(item => item.id === this.multipleSelection[0].id) === 0) {
          this.moveUpFlag = false
        }
        if (this.tableData.findIndex(item => item.id === this.multipleSelection[0].id) === this.tableData.length - 1) {
          this.moveDownFlag = false
        }
      }
    },
    removeData (id) {
      let ids = []
      if (id) {
        ids = [id]
      } else {
        ids = this.multipleSelection.map(item => item.id)
      }
      if (ids.length > 0) {
        this.$http.post(this.$http.defaults.shenghuohuiAPI + `api/` + this.tableName + `/remove`, {ids: ids}).then(response => {
          if (response.data.success === true) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          } else {
            console.log('删除失败:' + response.data.message)
            this.$message({
              message: '删除失败:' + response.data.message,
              type: 'error'
            })
          }
          this.getData()
        })
      } else {
        this.$message({
          message: '请至少选择一条信息',
          type: 'danger'
        })
      }
    },
    submitForm () {
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          let files = this.files.map(item => {
            let obj = {id: item.id, shenghuohuiId: localStorage.getItem('shenghuohuiId')}
            return obj
          })
          this.loading = true
          let para = {
            id: this.postForm.id,
            shenghuohuiunitId: localStorage.getItem('shenghuohuiunitId'),
            tongbaoshijian: this.postForm.tongbaoshijian,
            tongbaofangshi: this.postForm.tongbaofangshi,
            tongbaofanwei: this.postForm.tongbaofanwei,
            remark: this.postForm.remark,
            files: files
          }
          this.$http.post(this.$http.defaults.shenghuohuiAPI + `api/` + this.tableName + `/save`, para).then(response => {
            console.log(response.data.success)
            if (response.data.success === true) {
              this.$message({
                message: '保存成功',
                type: 'success'
              })
              if (this.$refs['postForm']) {
                this.$refs['postForm'].resetFields()
              }
              this.dialogVisible = false
              this.loading = false
              this.getData()
            } else {
              console.log('保存失败:' + response.data.message)
              this.$message({
                message: '保存失败:' + response.data.message,
                type: 'error'
              })
              this.loading = false
            }
          }).catch(error => {
            console.log(error)
            this.$message({
              message: '保存失败:' + error,
              type: 'error'
            })
            this.loading = false
          })
        }
      })
    },
    addData () {
      this.dialogtitle = '新增'
      this.dialogVisible = true
      this.postForm = Object.assign({}, defaultForm)
      if (this.$refs['postForm']) {
        this.$refs['postForm'].resetFields()
      }
      this.fileListEdit = []
      this.files = []
    },
    modData (id) {
      this.id = id
      this.dialogtitle = '编辑'
      this.dialogVisible = true
      this.infoLoading = true
      this.$http
        .get(this.$http.defaults.shenghuohuiAPI + `api/` + this.tableName + `/getById?id=` + id)
        .then(response => {
          this.infoLoading = false
          if (response.data.success === true) {
            console.log('获取成功')
            this.fileListEdit = []
            this.files = []
            this.postForm = Object.assign({}, response.data.result)
            this.postForm.fileList.forEach(item => {
              this.fileListEdit.push({url: this.$http.defaults.baseURL + this.$http.defaults.shenghuohuiAPI + 'api/newFileInfo/download?download=true&id=' + item.id, name: item.fileName.trim() + '.' + item.fileType, id: item.id})
              this.files.push({id: item.id})
            })
          } else {
            console.log('获取数据失败:' + response.data.message)
            this.$message({
              message: '获取数据失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
          this.infoLoading = false
        })
    },
    toggleSelection (id) {
      this.$nextTick(() => {
        if (id) {
          let newrow = this.tableData.find(item => item.id === id)
          console.log(newrow)
          this.$refs.multipleTable.toggleRowSelection(newrow)
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      })
    },
    getData (id) {
      this.listLoading = true
      let para = {
        shenghuohuiunitId: localStorage.getItem('shenghuohuiunitId'),
        pageNum: 1,
        pageSize: 2000
      }
      // var personParams = { Page: 0, Pagenum: 20, Personname: '', Unitkey: '', Sortkey: '', Isace: true, timestamp: new Date().getTime() }
      this.$http
        .post(this.$http.defaults.shenghuohuiAPI + `api/` + this.tableName + `/queryByPage`, para)
        .then(response => {
          this.pageLoading = false
          this.listLoading = false
          if (response.data.success === true) {
            console.log('获取成功')
            this.tableData = response.data.result.records
            if (id) {
              this.toggleSelection(id)
            }
          } else {
            console.log('获取数据失败:' + response.data.message)
            this.$message({
              message: '获取数据失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
          this.pageLoading = false
          this.listLoading = false
        })
    },
    tableresize (obj) {
      var clientHeight = 0
      if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      } else {
        clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      }
      obj.$nextTick(function () {
        obj.tableHeight = clientHeight - 200
      })
    }
  },
  mounted () {
    console.log('this.shhRemarkLength')
    console.log(this.shhRemarkLength)
    this.getData()
    this.tableresize(this)
    window.onresize = () => {
      // 通过捕获系统的onresize事件触发我们需要执行的事件
      this.tableresize(this)
    }
  }
}
</script>

<style>

  .shenghuohuiEdit .el-table th{
    font-weight: normal;
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
  }
  .shenghuohuiEdit .el-table td, .el-table th{
    padding:0;
    font-size:var(--size14) !important;
    line-height: 20px;
    font-family: '宋体'
  }
  .el-table{
    border-top: 1px solid #95B8E7 !important;
  }
  .el-table--border th, .el-table--border td {
    border-right: 1px solid #95B8E7 !important;
  }
  .el-table th.is-leaf, .el-table td {
    border-bottom: 1px solid #95B8E7 !important;
  }
  #shenghuohuiEditTable .mytable{
    border-top: 1px solid #74A6CC;
    border-left: 1px solid #74A6CC;
    margin: 10px;
    width: calc(100% - 20px);
    font-size:var(--size14) !important;
    font-family: '宋体'
  }
  #shenghuohuiEditTable .mytable th,
  #shenghuohuiEditTable .mytable td{
    height: auto;
    padding: 10px;
    border-right: 1px solid #74A6CC;
    border-bottom: 1px solid #74A6CC;
    vertical-align:top;
    line-height: 150%;
  }
  #shenghuohuiEditTable .mytable th{
    background:#C0DCF1;
    width:150px;
    vertical-align: middle;
  }
</style>
